package com.yonyou.pmclouds.workconnect.service.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.DateUtils;
import com.yonyou.pmclouds.basecom.util.SqlUtil;
import com.yonyou.pmclouds.constructiondiary.entity.ConstructionDiaryVO;
import com.yonyou.pmclouds.contacttype.entity.ContactTypeVO;
import com.yonyou.pmclouds.contacttype.service.rmiitf.ContactTypeRemoteMobService;
import com.yonyou.pmclouds.contacttype.service.rmiitf.ContactTypeRemoteService;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.pmpub.entity.QueryListParam;
import com.yonyou.pmclouds.pmpub.rmiitf.IPageQuerySerivce;
import com.yonyou.pmclouds.procedure.entity.ProcedureRefVO;
import com.yonyou.pmclouds.procedure.entity.ProcedureVO;
import com.yonyou.pmclouds.procedure.rmiitf.ProcedureQuery;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.workConnect.entity.WorkConReceiverVO;
import com.yonyou.pmclouds.workConnect.entity.WorkConnectVO;
import com.yonyou.pmclouds.workConnect.service.rmiitf.WorkConReceiverQuery;
import com.yonyou.pmclouds.workConnect.service.rmiitf.WorkConnectQuery;
import com.yonyou.pmclouds.workconnect.mapper.WorkConnectMapper;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

@Service(version = ApplicationConsts.APPLICATION_VERSION,interfaceClass=WorkConnectQuery.class)
public class WorkConnectQueryImpl implements WorkConnectQuery, IPageQuerySerivce<WorkConnectVO> {
    
    @Autowired
    private WorkConnectMapper workConnectMapper;

    @Autowired
    private WorkConReceiverQuery receiverQuery;
    
    @Autowired
    private ProjectSimpleQuery projectQuery;
    
    @Autowired
    private ProcedureQuery processQuery;
    
    @Autowired
    private ContactTypeRemoteMobService contypeMobQuery;

    @Autowired
    private ContactTypeRemoteService contypeQuery;
    
    @Autowired
    private PictureRemoteService picService;

    @Autowired
    private WorkConReceiverQuery workConReceiverQuery;

    @Autowired
    private OrganizationQuery organizationQuery;

    @Override
    public List<WorkConnectVO> selectByPkProject(String pk_project) throws BusinessException {
        List<WorkConnectVO> list = workConnectMapper.selectByPkProject(pk_project);
        getPictures(list); //添加照片
        return list;
    }

    /**
     * 添加照片
     */
    private void getPictures(List<WorkConnectVO> vos) throws BusinessException {
        if(vos == null || vos.size() == 0) return;
        List<String> pkBills = new ArrayList<>();
        for(WorkConnectVO vo : vos){
            if(vo != null && vo.getPk_workconnect() != null) pkBills.add(vo.getPk_workconnect());
        }
        if(pkBills.size() == 0) return;

        Map<String, List<String> > picMap = picService.queryPicsByPkEntitys(pkBills.toArray(new String[0]));
        if(picMap == null) return;

        for(WorkConnectVO vo : vos){
            if(vo != null && picMap.get(vo.getPk_workconnect()) != null){
                vo.setPictures(picMap.get(vo.getPk_workconnect()).toArray(new String[0]));
            }
        }
    }
    
    @Override
    public WorkConnectVO selectOne(String pk_workconnect) throws BusinessException {
        WorkConnectVO workConnectVO = workConnectMapper.getById(pk_workconnect);
        if(workConnectVO == null) {
            throw new BusinessException("该工作联系单不存在!");
        }
        if (StringUtils.isEmpty(workConnectVO.getPkReceiver())) {
            workConnectVO = setReceivers(workConnectVO);
        }
        workConnectVO = setPics(workConnectVO);
        return setRefFiledInfo(workConnectVO);
    }

    /**
     * 为workconnect设置workConReceiverVOS属性
     *
     * @param workConnectVO
     * @return
     */
    private WorkConnectVO setReceivers(WorkConnectVO workConnectVO) throws BusinessException {
        WorkConReceiverVO[] receiverVOS = receiverQuery.queryByWorkConnect(workConnectVO.getPk_workconnect());
        workConnectVO.setWorkConReceiverVOS(receiverVOS);
        return workConnectVO;
    }

    @Override
    public String[] queryPics(String pk_workconnect) throws BusinessException {
        return picService.queryPicNamesByPkEntity(pk_workconnect);
    }
    
    @Override
    public boolean queryRefByIds(String code, String[] ids) throws BusinessException {
        boolean flag = false;
        Integer count = workConnectMapper.selectRefByCode(code, ids);
        if(count != null && count > 0) {
            flag = true;
        }
        return flag;
    }

    @Override
    public PageObject<Object> queryByCondition(String[] pkProjects, String[] creators, String startDate, String endDate, int[] billStatus, int pageStart, int pageSize) throws BusinessException {

        int count = workConnectMapper.countByCondition(pkProjects, creators, startDate, endDate, billStatus);

        WorkConnectVO[] workConnectVOs = workConnectMapper.queryByCondition(pkProjects, creators, startDate, endDate, billStatus, pageStart, pageSize);

        return new PageObject<Object>(setRefFiledInfo(workConnectVOs),count,pageStart) ;
    }

    private WorkConnectVO setRefFiledInfo(WorkConnectVO vo) throws BusinessException  {
        // 联系类型
       ContactTypeVO typeVO = contypeMobQuery.queryById(vo.getPk_contacttype());
       vo.setContype_name(typeVO.getContype_name());
       // 工序
       String pk_process = vo.getPk_process();
       if(!StringUtils.isEmpty(pk_process)) {
           ProcedureVO procedureVO = processQuery.getById(pk_process);
           vo.setProcess_name(procedureVO.getSname());
       }
       // 项目
       ProjectVO projectVO = projectQuery.queryProject(vo.getPk_project());
       vo.setProject_name(projectVO.getSname());
       vo.setProject_code(projectVO.getScode());

        String pkOrg = projectVO.getPkOrg();
        if(StringUtils.isNotEmpty(pkOrg)) {
            OrganizationVO organizationVO = organizationQuery.queryByPkSrc(RuntimeEnvironment.getTenantId(), pkOrg);
            vo.setOrgName(organizationVO==null?null:organizationVO.getSname());
        }
        return vo;
    }
    
    private WorkConnectVO setPics(WorkConnectVO vo) throws BusinessException {
        vo.setPictures(queryPics(vo.getPk_workconnect()));
        return vo;
    }

    /**
     * 处理参照字段，非必输项需校验空
     *
     * @param vos
     * @return
     * @throws BusinessException
     */
    private WorkConnectVO[] setRefFiledInfo(WorkConnectVO[] vos) throws BusinessException {
        if (ArrayUtils.isEmpty(vos)) {
            return new WorkConnectVO[0];
        }

        Set<String> procSet = new HashSet<String>();
        Set<String> projectSet = new HashSet<String>();
        Set<String> pkSet = new HashSet<String>();
        Set<String> pkConType = new HashSet<String>();

        for (WorkConnectVO vo:
                vos) {
            procSet.add(vo.getPk_process());
            projectSet.add(vo.getPk_project());
            pkSet.add(vo.getPk_workconnect());
            pkConType.add(vo.getPk_contacttype());
        }

        Map<String,ProcedureRefVO>  procedureRefVOMap = processQuery.queryRefs(procSet.toArray(new String[0]));
        Map<String,ProjectVO> projectVOMap = projectQuery.queryProjects(projectSet.toArray(new String[0]));
        List<ContactTypeVO> contactTypeVOList = contypeQuery.queryConTypesByPK(pkConType.toArray(new String[0]));

        Map<String,List<String>> picMap = picService.queryPicsByPkEntitys(pkSet.toArray(new String[0]));

        Map<String,ContactTypeVO> contactTypeVOMap = new HashMap<String,ContactTypeVO>();

        for (ContactTypeVO contactTypeVO:
                contactTypeVOList) {
            contactTypeVOMap.put(contactTypeVO.getPk_contacttype(),contactTypeVO);
        }

        Map<String,List<String>> receiverMap = workConReceiverQuery.queryByPkConnects(pkSet.toArray(new String[0]));

        for (WorkConnectVO vo:
                vos) {
            vo.setProcess_name(procedureRefVOMap.get(vo.getPk_process()) == null ? null:procedureRefVOMap.get(vo.getPk_process()).getSname());
            vo.setProject_name(projectVOMap.get(vo.getPk_project()) == null ? null:projectVOMap.get(vo.getPk_project()).getSname());
            vo.setProject_code(projectVOMap.get(vo.getPk_project()) == null ? null:projectVOMap.get(vo.getPk_project()).getScode());
            vo.setContype_name(contactTypeVOMap.get(vo.getPk_contacttype()) == null ? null:contactTypeVOMap.get(vo.getPk_contacttype()).getContype_name());
            vo.setPkReceivers(receiverMap.get(vo.getPk_workconnect()) == null ? new String[0]:receiverMap.get(vo.getPk_workconnect()).toArray(new String[0]));
            vo.setPicNum(picMap.get(vo.getPk_workconnect()) == null ? 0 : picMap.get(vo.getPk_workconnect()).size());
        }

        return vos;
    }

    @Override
    public int countByProject(QueryListParam param) throws BusinessException{

        int count = workConnectMapper.countByCondition( new String[]{param.getPkProject()}, null,  param.getStartDate(), param.getEndDate(), null);

        return count;
    }

    @Override
    public WorkConnectVO[] queryByProject(QueryListParam param) throws BusinessException {
        WorkConnectVO[] vos = workConnectMapper.queryByCondition(new String[]{param.getPkProject()}, null,  param.getStartDate(), param.getEndDate(), null,param.getPageStart(),param.getPageSize());
        getPictures(Arrays.asList(vos));

        return vos;
    }

    @Override
    public String getBillType() {
        return BillTypeConst.WORKCONNECT_BILLTYPE;
    }
}
